package com.uid.util;

import com.xr.enums.IdType;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * ID生成工具类
 * 大概性能：4053506个/s
 * </p>
 *
 * @author Arnold Yang
 * @since 2018-11-16
 */
public final class IdUtil {

  // 用于控制nextId方法的并发访问
  private static final ReentrantLock lock = new ReentrantLock();

  private static final ConcurrentMap<IdType, IdGenerator> generatorMap = new ConcurrentHashMap<IdType, IdGenerator>();

  /**
   * 初始化IdType对应的IdGenerator
   */
  static {
    for(IdType type : IdType.values()){
      IdGenerator generator = new IdGenerator();
      generator.setGroupId(type.getCode());
      generatorMap.put(type, generator);
    }
  }

  /**
   * 获取id
   * @return
   * @throws Exception
   */
  public static long nextId() throws Exception {
    return nextId(IdType.DEFAULT);
  }

  public static long nextId(IdType type) throws Exception {
    lock.lock();
    try {
      return generatorMap.get(type).nextId();
    } catch (IllegalStateException ise){
      return nextId(type);
    } finally {
      lock.unlock();
    }
  }

  /**
   * 根据id获取生成时间
   * @param id
   * @return
   */
  public static long getTimestamp(long id) {
    return id >> IdGenerator.TIMESTAMP_SHIFT_BITS;
  }

  private IdUtil() {
  }
}
